package leetcode.code1981;

import java.util.HashSet;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.H;

/**
 * 执行用时：2091 ms, 在所有 Java 提交中击败了5.68%的用户
 * 
 * 内存消耗：57.1 MB, 在所有 Java 提交中击败了5.68%的用户
 * 
 * 通过测试用例：81 / 81
 * 
 * @date 2022年5月28日
 * @description
 */
public class Solution2 implements IDebug {

	public int minimizeTheDifference(int[][] mat, int target) {
		int m = mat.length, n = mat[0].length;
		Set<Integer>[] set = new HashSet[m];
		set[0] = new HashSet<>();
		for (int i = 0; i < n; i++) {
			set[0].add(mat[0][i]);
		}
		for (int i = 1; i < m; i++) {
			Set<Integer> cur = new HashSet<>();
			set[i] = cur;
			Set<Integer> last = set[i - 1];
			for (int l : last) {
				for (int j = 0; j < n; j++) {
					int num = mat[i][j];
					if (num + l < 4901) // 脑抽
						cur.add(num + l);
				}
			}
		}
		int ans = Integer.MAX_VALUE;
		for (int num : set[m - 1]) {
			ans = Math.min(ans, Math.abs(num - target));
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(1510, this.minimizeTheDifference(H.str2array1(
				"[[65],[45],[45],[69],[55],[60],[29],[25],[16],[5],[62],[16],[29],[19],[34],[2],[24],[32],[66],[62],[60],[46],[42],[37],[51],[4],[41],[4],[66],[20],[9],[4],[66],[6],[56],[10],[51],[44],[7],[8],[5],[44],[28],[7],[10],[7],[24],[62],[19],[14],[45],[68],[9],[14],[51],[28],[8],[57],[59],[6],[54],[8],[19],[16],[63],[45],[33],[15],[33],[67]]"),
				800));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
